<template>
  <div class="system-add-role-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px" center>
      <el-form ref="dicDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
        <el-row :gutter="35">
          <!-- 井选择 -->
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="井" filterable v-if="state.dialog.type==='add'">
              <el-select v-model="state.ruleForm.jid as any" placeholder="请选择井的位置" class="w100">
                <el-option
                    v-for="item in state.jList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="井" v-else>
              <el-select v-model="state.ruleForm.jid as any" placeholder="请选择井的位置" class="w100">
                <el-option
                    v-for="item in state.jList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 用户选择 -->
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="用户" filterable v-if="state.dialog.type==='add'">
              <el-select v-model.number="state.ruleForm.uid" placeholder="请选择" size="default" class="w100">
                <el-option
                    v-for="item in state.userList"
                    :key="item.id"
                    :label="item.name + '（' + item.phone + '）'"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="用户" v-else>
              <el-select v-model.number="state.ruleForm.uid" placeholder="请选择" size="default" class="w100">
                <el-option
                    v-for="item in state.userList"
                    :key="item.id"
                    :label="item.name + '（' + item.phone + '）'"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 开始时间 -->
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="开始时间" v-if="state.dialog.type==='add'">
              <el-date-picker
                  v-model="state.ruleForm.startTime"
                  type="datetime"
                  placeholder="请选择开始时间"
                  class="w100"
                  @change="handleTimeChange"
              />
            </el-form-item>
            <el-form-item label="开始时间" v-else>
              <el-date-picker
                  v-model="state.ruleForm.startTime"
                  type="datetime"
                  placeholder="请选择开始时间"
                  class="w100"
                  @change="handleTimeChange"
              />
            </el-form-item>
          </el-col>

          <!-- 结束时间 -->
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="结束时间" v-if="state.dialog.type==='add'">
              <el-date-picker
                  v-model="state.ruleForm.endTime"
                  type="datetime"
                  placeholder="请选择结束时间"
                  class="w100"
                  @change="handleTimeChange"
              />
            </el-form-item>
            <el-form-item label="结束时间" v-else>
              <el-date-picker
                  v-model="state.ruleForm.endTime"
                  type="datetime"
                  placeholder="请选择结束时间"
                  class="w100"
                  @change="handleTimeChange"
              />
            </el-form-item>
          </el-col>

          <!-- 刨除时间 -->
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="刨除时间" v-if="state.dialog.type==='add'">
              <el-input
                  v-model.number="state.ruleForm.excludeTime"
                  placeholder="请输入刨除时间"
                  clearable
                  @input="handleNumberInput"
              />
            </el-form-item>
            <el-form-item label="刨除时间" v-else>
              <el-input
                  v-model.number="state.ruleForm.excludeTime"
                  placeholder="请输入刨除时间"
                  clearable
                  @input="handleNumberInput"
              />
            </el-form-item>
          </el-col>

          <!-- 分钟价格 -->
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="分钟价格" v-if="state.dialog.type==='add'">
              <el-input
                  v-model.number="state.ruleForm.minutePrice"
                  placeholder="请输入分钟价格"
                  clearable
                  @input="handleNumberInput"
              />
            </el-form-item>
            <el-form-item label="分钟价格" v-else>
              <el-input
                  v-model.number="state.ruleForm.minutePrice"
                  placeholder="请输入分钟价格"
                  clearable
                  @input="handleNumberInput"
              />
            </el-form-item>
          </el-col>

          <!-- 应收金额（自动计算，禁止输入） -->
          <!--          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if='state.dialog.type="edit"'>-->
          <!--            <el-form-item label="应收金额">-->
          <!--              <el-input-->
          <!--                  v-model="receivablePrice"-->
          <!--                  placeholder="应收金额自动计算"-->
          <!--                  clearable-->
          <!--              />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!-- 应收金额（自动计算，禁止输入） -->
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <!--                  :value="state.dialog.type==='add'?computedTotalAmount:state.ruleForm.receivablePrice"-->
            <el-form-item label="应收金额">
              <el-input
                  :value="computedTotalAmount"
                  placeholder="应收金额自动计算"
                  clearable
                  :disabled="true"
              />
            </el-form-item>
          </el-col>
          <!-- 实收金额 -->
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.dialog.type==='edit'">
            <el-form-item label="实收金额">
              <el-input
                  v-model.number="state.ruleForm.netReceiptsPrice"
                  placeholder="请输入实收金额"
                  clearable
              />
            </el-form-item>
          </el-col>

          <!-- 支付状态 -->
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.dialog.type==='edit'">
            <el-form-item label="支付状态">
              <el-radio-group v-model="state.ruleForm.payStatus">
                <el-radio value="0">未支付</el-radio>
                <el-radio value="1">已支付</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- 支付受理人 -->
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.ruleForm.payStatus==='1'">
            <el-form-item label="支付受理人">
              <el-select
                  v-model="state.ruleForm.payTransactors" filterable clearable placeholder="请选择受理人"
                  style="width: 240px">
                <el-option
                    v-for="item in payTransactorsUserList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 备注 -->
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="备注" v-if="state.dialog.type==='add'">
              <el-input v-model="state.ruleForm.remake" placeholder="请输入备注" clearable
                        type="textarea" :rows="3" :max-rows="5"></el-input>
            </el-form-item>
            <el-form-item label="备注" v-else>
              <el-input v-model="state.ruleForm.remake" placeholder="请输入备注" clearable
                        type="textarea" :rows="3" :max-rows="5"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit(state.dialog.type == 'add' ? 'add' : 'edit')"
                     size="default">{{ state.dialog.submitTxt }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref, computed} from 'vue';
import {getJlist, getUserList, addRecord, updateRecord, getDetailRow} from '/@/api/jd/index'
import {formatDateNew} from '/@/utils/formatTime';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义表单引用和状态
const dicDialogFormRef = ref();

const payTransactorsUserList = [
  {
    value: '红女',
    label: '红女',
  },
  {
    value: '改英',
    label: '改英',
  },
]
const state = reactive({
  ruleForm: {
    jid: '',          // 井ID（数字类型
    uid: '',          // 用户ID（数字类型）
    startTime: '',  // 开始时间（Date类型）
    endTime: '',    // 结束时间（Date类型）
    excludeTime: 0,   // 刨除时间（数字类型，单位：分钟）
    minutePrice: 2,   // 分钟价格（数字类型，单位：元/分钟）
    receivablePrice: '',   // 分钟价格（数字类型，单位：元/分钟）
    netReceiptsPrice: '',   // 分钟价格（数字类型，单位：元/分钟）
    remake: '',       // 备注
    id: '',
  },
  jList: [],// 井列表
  userList: [],// 用户列表
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  param: {
    "pageNum": 1,
    "pageSize": 9999
  },
});

// 计算应收金额的计算属性（响应所有相关字段变化）
const computedTotalAmount = computed(() => {
  // 校验必填字段
  if (!state.ruleForm.startTime || !state.ruleForm.endTime) {
    return '0.00';
  }
  // 计算总时间差（分钟）
  const timeDiff = getTimeDiffInMinutes(
      state.ruleForm.startTime,
      state.ruleForm.endTime
  );

  // 计算有效时间（总时间 - 刨除时间，最小值为0）
  const effectiveTime = Math.max(timeDiff - state.ruleForm.excludeTime, 0);

  // 计算总金额（保留两位小数）
  return (state.ruleForm.minutePrice * effectiveTime).toFixed(2);
});

// 辅助函数：计算两个时间的分钟差
const getTimeDiffInMinutes = (start: Date, end: Date): number => {
  // 将输入统一转换为 Date 对象
  const startDate = new Date(start);
  const endDate = new Date(end);
  const diffMs = endDate.getTime() - startDate.getTime();
  console.log(diffMs);
  return Math.floor(diffMs / (1000 * 60)); // 转换为分钟
};

// 输入框数字校验（防止输入非数字）
const handleNumberInput = (e: Event) => {
  const target = e.target as HTMLInputElement;
  target.value = target.value.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
};

// 时间选择变化时触发计算（确保时间字段更新时立即计算）
const handleTimeChange = () => {
  // 强制触发计算属性更新（可选，计算属性会自动响应依赖变化）
  computedTotalAmount.value;
};

//获取井得列表
const getJlistData = async () => {
  const res = await getJlist(state.param);
  state.jList = res.data.rows;
}
//获取用户列表
const getUserListData = async () => {
  const res = await getUserList(state.param);
  state.userList = res.data.rows;
}
// 打开弹窗
const openDialog = async (type: string, row?: any) => {
  console.log(typeof (type))
  state.dialog.isShowDialog = true;
  state.dialog.type = type;
  getJlistData()
  getUserListData()
  if (type === 'edit') {
    const param = {id: row.id}
    const res = await getDetailRow(param)
    // 处理编辑场景：转换时间字符串为Date对象
    console.log(res)
    state.ruleForm = {
      id: res.data.data.id,
      jid: res.data.data.jid,
      uid: res.data.data.uid,
      excludeTime: res.data.data.excludeTime,
      payStatus: res.data.data.payStatus.toString(),
      payTransactors: res.data.data.payTransactors,
      minutePrice: res.data.data.minutePrice,
      netReceiptsPrice: res.data.data.netReceiptsPrice,//实
      receivablePrice: res.data.data.receivablePrice, //应
      startTime: formatDateNew(res.data.data.startTime),
      endTime: formatDateNew(res.data.data.endTime),
      remake: res.data.data.remake,
    };
    state.dialog.title = '修改记录';
    state.dialog.submitTxt = '修 改';
  } else {
    // 新增场景：重置表单
    state.ruleForm = {
      jid: '',
      uid: '',
      startTime: '',
      endTime: '',
      excludeTime: 0,
      minutePrice: 2,
      remake: '',
    };
    state.dialog.title = '新增记录';
    state.dialog.submitTxt = '新 增';
  }
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};

// 取消操作
const onCancel = () => {
  closeDialog();
};

// 提交操作
const onSubmit = (type: any) => {
  // 示例：打印最终表单数据（实际项目中替换为接口调用）
  console.log('提交的数据：', state.ruleForm);
  if (type === 'add') {
    state.ruleForm = {
      jid: state.ruleForm.jid,
      uid: state.ruleForm.uid,
      startTime: formatDateNew(state.ruleForm.startTime),
      endTime: formatDateNew(state.ruleForm.endTime),
      excludeTime: state.ruleForm.excludeTime,
      minutePrice: state.ruleForm.minutePrice,
      remake: state.ruleForm.remake,
    }
    addRecord(state.ruleForm)
  } else {
    updateRecord(state.ruleForm)
  }
  closeDialog();

  setTimeout(() => {
    state.dialog.isShowDialog = false;
  }, 1000);

  emit('refresh');
};

// 暴露组件方法
defineExpose({
  openDialog,
});
</script>

<style scoped>
/* 可选：输入框禁用时的样式调整 */
.el-input[disabled] {
  background-color: #f5f7fa;
  cursor: not-allowed;
}

</style>
